﻿using UnityEngine;
using UnityEngine.Serialization;

namespace Pathfinding
{
    public class OctreeBuilder : MonoBehaviour
    {
        public Collider[] allColliders;                        //场景包含的全部对象
        public Octree Octree;                                  // 八叉树
        [SerializeField] private bool isSeeOne = false;        //是否只观察一个分裂后的节点
        [SerializeField] private bool isDrawOctreeCube = true; //是否绘制二叉树
        [SerializeField] private bool isDrawNode = true;       // 是否要绘制图的节点
        [SerializeField] private bool isDrawEdge = true;       // 是否要绘制图的边

        private void Awake()
        {
            allColliders = FindObjectsOfType<Collider>();
            Debug.Log(Time.realtimeSinceStartup);
            Octree = new Octree(allColliders, new Graph<OctreeNode, int>());
            Debug.Log(Time.realtimeSinceStartup);
        }

        private void OnDrawGizmos()
        {
            if (!Application.isPlaying) return;
            if (isDrawOctreeCube)
            {
                Octree.RootNode.Draw(isSeeOne);
            }

            DrawGraph();
        }

        private void DrawGraph()
        {
            if (isDrawEdge)
            {
                foreach (var edge in Octree.NavGraph.EdgeList)
                {
                    Gizmos.color = new Color(0.6f, 0, 0, 0.1f);
                    Gizmos.DrawLine(edge.Key.Item1.NodeCube.center,
                        edge.Key.Item2.NodeCube.center);
                }
            }

            if (!isDrawNode) return;
            foreach (var node in Octree.NavGraph.NodeSet)
            {
                Gizmos.color = new Color(1, 1, 0, 1f);
                Gizmos.DrawWireSphere(node.NodeCube.center, 0.25f);
            }
        }
    }
}